package com.stockz.downloader.breadth;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.stockz.downloader.util.DownloaderConstant;
import com.stockz.equity.manager.BarManager;
import com.stockz.equity.manager.ConfigurationManager;
import com.stockz.equity.model.Bar;
import com.stockz.equity.model.Configuration;
import com.stockz.equity.util.CoreConstant;

@Component
public class BarListBreadthDownloadPersistenceCallback<T extends BarListBreadthDownload<V,U>,V extends List<U>,W, U extends Bar> implements
	BarListBreadthDownloaderCallback<T,V,W,U> {
	private static Logger logger = Logger.getLogger(BarListBreadthDownloadPersistenceCallback.class);
	
	@Autowired
	private BarManager barManager;
	@Autowired
	private ConfigurationManager configurationManager;
	
	@Override
	public void execute(T download, W customPayload) {
		logger.trace(this.getClass().getName()+" called");
		
		if(download != null 
				&& !download.getBarList().isEmpty()
				&& DownloaderConstant.ACTION.PARSE.equals(download.getAction())
				&& DownloaderConstant.EVENT.SUCCESS.equals(download.getEvent())){
			logger.warn("Null or Empty Bar list was passed to the PersistenceCallback");
		}else{
			logger.trace("Bar List size to persist : "+download.getBarList().size());
			barManager.persistAll(download.getBarList());
			logger.trace("Successfully persisted Bar List of size "+download.getBarList().size());
			configurationManager.persist(new Configuration(DownloaderConstant.LAST_BSE_BREDTH_DOWNLOAD_DATE,
					CoreConstant.dateFormat.format(download.getDownloadDate())));
			logger.info("Successfully updated last download date as "+download.getDownloadDate());
		}
	}
}
